package com.lcf.app.minio.demo;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class ObjectDemo {

    static MinioClient minioClient =
            MinioClient.builder()
                    .endpoint("http://192.168.254.18:9000")
                    .credentials("minioadmin", "minioadmin")
                    .build();

    public static void main(String[] args)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {
            //上传文件到桶
            String bucketName = "my-bucket" ;// 桶名称
            String objectName = "dddd.jpg" ;// 对象名称
            String fileName = "D:\\dddd.jpg" ;// 文件
//            minioClient.uploadObject(
//                    UploadObjectArgs.builder()
//                            .bucket(bucketName)
//                            .object(objectName)
//                            .filename(fileName)
//                            //.sse() // 加密
//                            .build());
            File file = new File(fileName);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(new FileInputStream(file), FileUtils.sizeOf(file), -1).build());
            System.out.println("文件上传成功。");
            Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
            System.out.println("文件列表：");
            for (Result<Item> v : results) {
                Item item = v.get();
                System.out.println(item.objectName());
            }
            //下载文件
            //minioClient.downloadObject(DownloadObjectArgs.builder().bucket(bucketName).object(objectName).filename("下载文件地址").build());
            GetObjectResponse response = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
            System.out.println("文件下载成功。");
            IOUtils.copy(response, new FileOutputStream("D:/" + response.object()));

            String presignedObjectUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .method(Method.GET)
                    .expiry(60, TimeUnit.SECONDS)
                    .build());
            System.out.println("获取临时路径：" + presignedObjectUrl);
            //删除文件
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            System.out.println("文件删除成功。");

        } catch (MinioException e) {
            e.printStackTrace();
        }
    }

}
